var AclComm = {
    Url: CTX + '/sys/acl'
};
var AclMVC = {
    Req: {
        list: {method: 'GET', url: AclComm.Url},
        add: {method: 'POST', url: AclComm.Url},
        update: {method: 'PUT', url: AclComm.Url},
        del: {method: 'DELETE', url: AclComm.Url},
        // TODO 还没有考虑清楚tree grid的导出该怎么做
        export: {method:'POST', url: AclComm.Url + '/export'},
        findUserAndRole: {method: 'GET', url: AclComm.Url + '/findUserAndRole'}
    },
    DOMs: null,
    data: {},
    Columns: {
        acl: [[{
            field: '_opts_',
            title: '操作',
            width: 100,
            align: 'center',
            formatter: function (v, row) {
                var ary = [];
                ary.push('<a href="javascript:;" permission="sys:acl:update" class="row-btn" title="修改" onclick="update(\'' + row.id + '\')"><i class=" fa fa-edit"></i></a>');
                ary.push('<a href="javascript:;" permission="sys:acl:del" class="row-btn" title="删除" onclick="deletes(\'' + row.id + '\')"><i class="fa fa-trash"></i></a>');
                ary.push('<a href="javascript:;" class="row-btn" title="关联信息" onclick="relatedUserAndRole(\'' + row.id + '\')"><i class="fa fa-info-circle"></i></a>');
                return ary.join('&nbsp;<span class="btn-separator"></span>&nbsp;');
            }
        }, {
            field: 'name',
            title: '权限名称',
            width: 180,
            formatter: function (v, row) {
                return '<a href="javascript:;" class="row-btn" title="' + row.name + '" onclick="see(\'' + row.id + '\')">' + v + '</a>';
            }
        }, {
            field: 'enname',
            title: '权限英文名',
            width: 150
        }, {
            field: 'value',
            title: '权限值',
            width: 150
        }, {
            field: 'parentId',
            title: '父权限',
            width: 150,
            formatter: function (v, row) {
                if (v == 0) {
                    return '';
                }
                var acl = aclMap[v];
                if (acl && acl.id == v) {
                    return acl.name;
                }
                return v;
            }
        }, {
            field: 'type',
            title: '权限类型',
            width: 80,
            formatter: function (v, row) {
                var d = typeMap[v];
                return d ? $.app.formatString('<span title="{0}"> {0}</span>', d) : v;
            }
        }, {
            field: 'icon',
            title: '图标',
            width: 50,
            formatter: function (v, row) {
                return $.app.formatString('<i class="{0}"></i>', v);
            }
        }, {
            field: 'seq',
            title: '顺序',
            width: 50
        }, {
            field: 'url',
            title: 'URL',
            width: 200
        }, {
            field: 'note',
            title: '备注',
            width: 150
        }]]
    }
};

// key和实体的映射，用于grid字段的format
var aclMap = {};
var typeMap = {};

// 查询表单和编辑表单用到的下拉数据
var typeList = [];

var $grid = null;
var $dlg = null;

$(function () {
    AclMVC.DOMs = {
        $searchForm: $('#searchForm'),
        $searchBtn: $('#searchBtn'),
        $resetBtn: $('#resetBtn'),
        $dataGrid: $('#aclGrid'),
        $dlg: $('#dlg')
    };

    $grid = AclMVC.DOMs.$dataGrid;
    $dlg = AclMVC.DOMs.$dlg;

    ajaxEnum('com.uvnos4j.matilda.system.enums.AclType', function (dict) {
        typeMap = dict._map;
        typeList = dict._list;
        initAclTreeGrid();
        $('#fm_type').combobox({
            data: typeList,
            value: 1
        });
    });

    AclMVC.DOMs.$searchBtn.click(function () {
        var params = getQueryParams();
        $grid.treegrid('load', params);
    });

    AclMVC.DOMs.$resetBtn.click(function () {
        $('#searchForm').form('reset');
        $('#searchBtn').trigger('click');
    });
});

function getQueryParams() {
    var params = $('#searchForm').serializeForm();
    return params;
}

function initAclTreeGrid() {
    $grid.treegrid({
        fit: true,
        //fitColumns: true,
        idField: 'id',
        treeField: 'name',
        method: AclMVC.Req.list.method,
        url: AclMVC.Req.list.url,
        queryParams: getQueryParams(),
        sortName: 'seq',
        sortOrder: 'asc',
        columns: AclMVC.Columns.acl,
        loadFilter: function (data, parentId) {
            if (data.data) {
                var gridData = data.data;
                refreshParentId(gridData);
                return gridData;
            } else {
                return data;
            }
        },
        // onSelect: function (row) {
        //     relatedUserAndRole(row.id);
        // },
        onLoadSuccess: function (row, data) {
            $.app.controlPermission();
            // 执行一次，权限较多默认收起子节点
            $grid.treegrid('collapseAll');
            if (data && data.length > 0) {
                var id = data[0].id;
                $grid.treegrid('select', id);
            }
        },
        onContextMenu: function (e, row) {
            e.preventDefault();
            $grid.treegrid('select', row.id);
            $('#cm').menu('show', {
                left: e.pageX,
                top: e.pageY
            });
        }
    });
}

/**
 * 新增、修改、删除后以及grid刷新前，刷新父权限信息（列表、编辑表单）
 * @param treeGridData 包含全部权限信息
 */
function refreshParentId(treeGridData) {
    if (!treeGridData) {
        treeGridData = $grid.treegrid('getData');
    }
    // 将tree grid数据转换为 id-name的map数据，用于treegrid列表
    changeTreeGrid2Map(treeGridData, 'id', 'name', 'children', aclMap);
    // 将tree grid结构处理成easyui tree可用的数据，构造combotree
    var treeData = changeTreeGrid2TreeData(treeGridData, 'id', 'name', 'children');
    treeData = e_tree_addall_filter(treeData, {id: 0, text: ''});
    $('#fm_parentId').combotree({
        data: treeData,
        value: 0
    });
}

/**
 * 向tree grid 中添加一行，并排序
 * @param rowData
 */
function addTreeGridRow(rowData) {
    var parentId = rowData.parentId;
    // 1.获取添加行父节点下的同级数据
    var children = [];
    if (rowData.root) {
        children = $grid.treegrid('getRoots');
    } else {
        children = $grid.treegrid('getChildren', parentId);
    }
    var filterChildren = $.grep(children, function (child, i) {
        return child.parentId === parentId;
    });

    // 2.删除添加行父节点下的同级行信息
    if (rowData.root) {
        $grid.treegrid('loadData', []);
    } else {
        $.each(filterChildren, function (i, c) {
            $grid.treegrid('remove', c.id);
        });
    }

    // 3.同级数据中加入新添加行并排序
    filterChildren.push(rowData);
    filterChildren.sort(function (a, b) {
        return a.seq - b.seq;
    });

    // 4.将排序后的同级数据添加到父节点下
    $grid.treegrid('append', {
        parent: parentId,
        data: filterChildren
    });
}

function add(parentId) {
    var $form = $dlg.find('form');
    $form.form('reset');

    if (parentId || parentId === 0) {// 顶级节点的parent id===0
        $form.form('load', {parentId: parentId});
    }

    $dlg.dialog({
        title: '新增权限',
        modal: true,
        inline: true,
        buttons: [{
            text: '确定',
            iconCls: 'e-icon fa fa-save',
            plain: true,
            handler: function () {
                var formObj = $form.serializeForm();
                $form.submitEForm(AclMVC.Req.add, formObj, function (vo) {
                    formObj.id = vo.id;
                    formObj.code = vo.code;
                    addTreeGridRow(formObj);
                    refreshParentId();
                    $dlg.dialog('close');
                });
            }
        }, {
            text: '关闭',
            iconCls: 'fa fa-close',
            plain: true,
            handler: function () {
                $dlg.dialog('close');
            }
        }]
    }).dialog('open');
}

function addSameLevel() {
    var row = $grid.treegrid('getSelections')[0];
    var parent = $grid.treegrid('getParent', row.id);
    // 选择根节点（系统管理）时，parent不存在
    if (parent) {
        add(parent.id);
    } else {
        add();
    }
}

function addDownLevel() {
    var row = $grid.treegrid('getSelections')[0];
    add(row.id);
}

// 针对行内触发和非行内触发两种情况
function update(id) {
    var row = null;
    if (id || id === 0) {// 考虑到存在id===0的情况
        row = aclMap[id];
    } else {
        row = $grid.treegrid('getSelections')[0];
    }
    if (!row) {
        $.showMsg('请选择一行数据！');
        return;
    }

    var $form = $dlg.find('form');
    $form.form('load', row);
    $dlg.dialog({
        title: '修改权限',
        modal: true,
        buttons: [{
            text: '确定',
            iconCls: 'fa fa-save',
            plain: true,
            handler: function () {
                var formObj = $form.serializeForm();
                $form.submitEForm(AclMVC.Req.update, formObj, function (id) {
                    var newRow = $.extend(true, {}, row, formObj);
                    $grid.treegrid('remove', row.id);
                    addTreeGridRow(newRow);
                    refreshParentId();
                    // 如果修改的时权限名称treeField字段时，需要更新其直接下级节点展示的父节点名称
                    if (row.name != formObj.name) {
                        var children = $grid.treegrid('getChildren', row.id);
                        if (!children) {
                            children = [];
                        }
                        var filterChildren = $.grep(children, function (child, i) {
                            return child.parentId == row.id;
                        });
                        $.each(filterChildren, function (i, c) {
                            $grid.treegrid('update', {id: c.id, row: c});
                        });
                    }
                    $dlg.dialog('close');
                });
            }
        }, {
            text: '关闭',
            iconCls: 'fa fa-close',
            plain: true,
            handler: function () {
                $dlg.dialog('close');
            }
        }]
    }).dialog('open');
}

function see(id) {
    var row = aclMap[id];

    $dlg.find('form').form('load', row);
    $dlg.dialog({
        title: '查看权限',
        modal: true,
        buttons: [{
            text: '关闭',
            iconCls: 'fa fa-close',
            plain: true,
            handler: function () {
                $dlg.dialog('close');
            }
        }]
    }).dialog('open');
}

function deletes(id) {
    if (id || id === 0) {// 考虑到存在id===0的情况
        var row = aclMap[id];
        $.confirmMsg('确定要删除权限[' + row.name + ']吗？', function () {
            doDelete([row.id]);
        });
    } else {
        var rows = $grid.treegrid('getSelections'), ids = [];
        if (rows && rows.length) {
            $.each(rows, function (i, row) {
                ids.push(row.id);
            });
            $.confirmMsg('确定要删除选择的[' + ids.length + ']条记录？', function () {
                doDelete(ids);
            });
        } else {
            $.showMsg('请选择要删除的记录');
        }
    }
}

function doDelete(ids) {
    $.ajax({
        type: AclMVC.Req.del.method,
        url: AclMVC.Req.del.url,
        data: {
            ids: ids.join(',')
        },
        dataType: 'json',
        success: function (result) {
            $.dealResultData(result, function (data) {
                $.each(ids, function (i, id) {
                    $grid.treegrid('remove', id);
                });
                refreshParentId();
            });
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            $.dealResultData(XMLHttpRequest.responseJSON);
        }
    });
}

function relatedUserAndRole(aclId) {
    var acl = aclMap[aclId];
    var n = $('#aclRelatedLayout').layout('panel', 'north');
    var c = $('#aclRelatedLayout').layout('panel', 'center');
    n.panel('setTitle', '[' + acl.name + ']关联角色列表');
    c.panel('setTitle', '[' + acl.name + ']关联用户列表');
    $.ajax({
        type: AclMVC.Req.findUserAndRole.method,
        url: AclMVC.Req.findUserAndRole.url,
        data: {
            aclId: acl.id
        },
        dataType: 'json',
        success: function (data) {
            if (data && data.status) {
                if (data.status == '200') {
                    var roleData = data.data.roleList;
                    $('#aclRoleGrid').datagrid('loadData', roleData);
                    var userData = data.data.userList;
                    $('#aclUserGrid').datagrid('loadData', userData);
                } else {
                    $.errorMsg(data.msg);
                }
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            $.dealResultData(XMLHttpRequest.responseJSON);
        }
    });
}





